<?php
//CF_Controllers_Action
class IndexController extends CF_Controller_Action
{

	public function deleteAction()
	{
		$this->view->title = "Delete product";
		$this->view->headTitle($this->view->title);

		if ($this->getRequest()->isPost()) {
			$del = $this->getRequest()->getPost('del');
			if ($del == 'yes') {
				$id = $this->getRequest()->getPost('id');
				$product = new Project_Product_Table();
				$product->deleteProduct($id);

				$photoDB = new Project_Photo_Table();
				$productImages = $photoDB->getProductPhotos($id);

				$this->_deleteProductImages($productImages);
				$photoDB->deleteProductPhotos($id);
			}
			$this->_helper->redirector('index');
		} else {
			$id = $this->_getParam('id', 0);
			$product = new Project_Product_Table();
			$this->view->product = $product->getProduct($id);
		}
	}

	function addAction()
	{
		$this->view->title = "Add new product";
		$this->view->headTitle($this->view->title);

		$form = new Application_Form_Product();
		$form->submit->setLabel('Add');
		$this->view->form = $form;

		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {

				$productData = array();
				$productData['register_date'] = $form->getValue('date');
				$productData['category_id'] = $form->getValue('category_id');
				$productData['model'] = $form->getValue('model');
				$productData['description'] = $form->getValue('description');
				$productData['price'] = $form->getValue('price');
				$productData['quantity'] = $form->getValue('quantity');
				$products = new Project_Product_Table();
				$products->addProduct($productData);

				$productID = $products->getAdapter()->lastInsertID();

				$photo = new Project_Photo_Table();
				$photoData = $this->_fileUploader($form, $productID);
				$photo->addProductPhoto($photoData);

				$this->_helper->redirector('index');
			} else {
				$form->populate($formData);
			}
		}
	}

	function editAction()
	{
		$this->view->title = "Edit product";
		$this->view->headTitle($this->view->title);

		$form = new Application_Form_Product();
		$form->submit->setLabel('Save');
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			$id = (int)$this->_getParam('id');
			$products = new Project_Product_Table();
			$this->view->productModel = $products->getProduct($id);
			if ($form->isValid($formData)) {
				if(!isset($id)){
					$this->_helper->redirector('index');
				}
				$productData = array();
				$productData['register_date'] = $form->getValue('date');
				$productData['category_id'] = $form->getValue('category_id');
				$productData['model'] = $form->getValue('model');
				$productData['description'] = $form->getValue('description');
				$productData['price'] = $form->getValue('price');
				$productData['quantity'] = $form->getValue('quantity');
				$productData['id'] = $id;
				$products =  new Project_Product_Table();
				$products->updateProduct($productData);

				$photoDB = new Project_Photo_Table();

				//delete old images from dir
				$productImages = $photoDB->getProductPhotos($id);


				//upload image into new path from temp if it has been modified


					$photoData = $this->_fileUploader($form, $id);
					$photoDB->editProductPhoto($photoData);
					$this->_deleteProductImages($productImages);


				$this->_helper->redirector('index');
			} else {
				$form->populate($formData);
				$photoDB = new Project_Photo_Table();
				$this->view->imageLinks = $photoDB->getProductPhotos($id);
			}
		} else {
			$id = $this->_getParam('id', 0);
			$products = new Project_Product_Table();
			$this->view->productModel = $products->getProduct($id);
			if ($id > 0) {
				$products = new Project_Product_Table();
				$product = $products->getProduct($id);
				$form->setDefaults(array(
					'category_id' => $product->category_id,
					'model' 	  => $product->model,
					'description' => $product->description,
					'price'       => $product->price,
					'quantity'    => $product->quantity,
					'date'  	  => $product->register_date
				));
				$photoDB = new Project_Photo_Table();

				$this->view->imageLinks = $photoDB->getProductPhotos($id);
			}
		}
	}

	/**
	 *
	 * delete product images
	 * @param array $filenames
	 * @return array deleted files
	 */
	private function _deleteProductImages(array $filenames){
		$productPath = dirname('.').
					DIRECTORY_SEPARATOR.
					'images'.
					DIRECTORY_SEPARATOR.
					'products'.
					DIRECTORY_SEPARATOR;
		$files = scandir($productPath);
		$deletedFiles = array();
		foreach ($filenames as $file) {
			if(in_array($file->link, $files)){
				unlink($productPath.$file->link);
				$deletedFiles[] = $file->link;
			}
		}
		if(!empty($deletedFiles)){
			return $deletedFiles;
		}else{
			return false;
		}
	}

	/**
	 * create new upload path with renaming of filename
	 * and upload it into this path
	 *
	 * @param Application_Form_Product $form
	 * gives file Adapter
	 * @param int $productID
	 * @return array $photoData
	 */
	private function _fileUploader(Application_Form_Product $form, $productID){

		//if(!is_null($form->getElement('image')->getValue())){
			$fileAdapter = $form->getElement('image')->getTransferAdapter();
			$fileInfo = $fileAdapter->getFileInfo();
			$ext = pathinfo($fileInfo['image']['name'],PATHINFO_EXTENSION);
			$newFileName = $form->getValue('model');
			$newFileName .= rand(0,100);
			$newFileName .= '.'.$ext;
			$newPath = dirname('.').
			DIRECTORY_SEPARATOR.
			'images'.
			DIRECTORY_SEPARATOR.
			'products'.
			DIRECTORY_SEPARATOR.
			$newFileName;
			$fileAdapter->addFilter('Rename', $newPath);
			//replace from temp into new path
			$fileAdapter->receive();
			$photoData = array(
			'product_id' => $productID,
			'link'       => $newFileName
			);
			return $photoData;
		//}else{
			//return false;
		//}

	}

	public function indexAction()
	{
		$this->view->title = "Products";
		$this->view->headTitle($this->view->title);
		$products = new Project_Product_Table();
		$this->view->products = $products->getProducts();
		$categoryDb = new Project_Category_Table();
		$categories = $categoryDb->getCategories();
		$this->view->categories = $categories;
	}

	private function _getSortParam($key)
	{
		$sortParam = $this->getRequest()->getParam(key);
		if(empty($sortParam)){
			return false;
		}
		return $this->_cleanParam($sortParam);
	}

	private function _cleanParam($param)
	{
		return htmlspecialchars(trim($param));
	}
}
//print_r(Zend_Registry::get('acl'));






